package org.example;

import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureWriter;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateShapefile {

    public static void main(String[] args) throws Exception {
        // 1. 定义要素类型（FeatureType）
        SimpleFeatureType featureType = DataUtilities.createType(
                "Location",
                "geometry:Point:srid=4326,name:String"// ok,创建shp,几何字段要放在第一位，属性放在后面，否则字段对于报错！
//                "name:String,geometry:Point:srid=4326"// 写入shp时，字段对应错误报错
        );


        // 2. 创建示例数据
        List<SimpleFeature> features = new ArrayList<>();
        GeometryFactory geometryFactory = new GeometryFactory();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);

        // 添加第一个点要素
        Point point1 = geometryFactory.createPoint(new Coordinate(116.39, 39.91));
        featureBuilder.add(point1);
        featureBuilder.add("北京");
        features.add(featureBuilder.buildFeature(null));

        // 添加第二个点要素
        Point point2 = geometryFactory.createPoint(new Coordinate(121.47, 31.23));
        featureBuilder.add(point2);
        featureBuilder.add("上海");
        features.add(featureBuilder.buildFeature(null));

        // 3. 创建 Shapefile 存储
        File shapefile = new File("gisdata/geotools/createshp/locations.shp");
        URL shapefileURL = shapefile.toURI().toURL();

        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

        Map<String, Serializable> params = new HashMap<>();
        params.put(ShapefileDataStoreFactory.URLP.key, shapefileURL);
        params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);

        ShapefileDataStore dataStore =
                (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);

        // 4. 设置要素类型（定义字段结构）
        dataStore.createSchema(featureType);
        // 5. 写入数据
        Transaction transaction = new DefaultTransaction("create");

       // 使用 FeatureWriter 代替 SimpleFeatureWriter
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
                dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], transaction);

        for (SimpleFeature feature : features) {
            SimpleFeature newFeature = writer.next();// 固定的，：the_geom name
            newFeature.setAttributes(feature.getAttributes());//feature，根据定义的featureType，设置属性 geometry name||name geometry
            writer.write();
        }

        writer.close();
        transaction.commit();
        transaction.close();
        dataStore.dispose();

        System.out.println("Shapefile 创建成功！");
    }
}